package com.hmjk.health.background.data;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.DEV_POWER;

public class DevicePowerUpdated extends DataUpdated{
	private static String TAG = DevicePowerUpdated.class.getSimpleName();
	private HashMap<String, POWER_DATA> mDataMap = new HashMap<String, POWER_DATA>();
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	class POWER_DATA{
		String tid;
		int power = -1;
		long update = 0;
		
		POWER_DATA(String tid){
			tid = tid;
		}
	}
	
	public DevicePowerUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
	}

	@Override
	public void setUserData(Object data) {
		reqTime = 0;
		upTime = 0;
	}

	@Override
	public long delay() {
		// TODO Auto-generated method stub
		return -1;
	}

	@Override
	public boolean grab() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean grabByUser() {
		// TODO Auto-generated method stub
		return false;
	}

	private void doRequest(String uid, String tid){			
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		
		si.putExtra("sub_act", NetService.GET_DEVICE_POWER);
		si.putExtra("uid", uid);
		
		si.putExtra("tidarr", "[\""+tid+"\"]");
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_DEVICE_POWER" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	@Override
	public boolean grabByUserWithSingleArgs(Object args){
		if(args == null)
			return false;
		
		String tid = (String)args;
		if(tid.trim().isEmpty())
			return false;
		
		String uid = mApp.getUID();
		logd("grabByUserWithSingleArgs uid="+uid);
		if(uid == null)
			return false;
		
		POWER_DATA data = mDataMap.get(tid);
		long curMs = System.currentTimeMillis();
		if(data != null){
			if((curMs - data.update) < MIN_QUERY_DUR * 1000){
				logd("grabByUserWithSingleArgs wait for " + MIN_QUERY_DUR + "s");
				return false;
			}
		}else{
			data = new POWER_DATA(tid);
			mDataMap.put(tid, data);
		}
		
		doRequest(uid, tid);
		data.update = curMs;
		logd("grabByUserWithSingleArgs req sent!");
		return true;
	}
	
	@Override
	public void receive(String stamp, String sjson) {
		if(stamp.startsWith("GET_DEVICE_POWER") == false)
			return;
		
		if(sjson != null){
			boolean update = false;
			JSONArray tidarrs = null;
			try {
				JSONObject json = new JSONObject(sjson);
				int code = json.getInt("code");
				JSONObject sd = json.getJSONObject("senddata");
				tidarrs = sd.getJSONArray("tidarr");
				if(code == 200){
					String state = json.getString("state");
					if(state.equalsIgnoreCase("00")){
						JSONObject recdata = json.getJSONObject("recdata");	
						
						long curtime = System.currentTimeMillis();
						if(recdata != null){
							if(recdata.has("powerarr")){
								JSONArray array = recdata.getJSONArray("powerarr");
								int len = array.length();
								if(len > 0)
									update = true;
								for(int i=0; i<len; i++){
									JSONObject o = array.getJSONObject(i);
									String tid = o.getString("tid");
									String power = o.getString("power");
									
									POWER_DATA pd = mDataMap.get(tid);
									if(pd == null){
										pd = new POWER_DATA(tid);
										mDataMap.put(tid, pd);
									}
									pd.power = Integer.parseInt(power);
									pd.update = curtime;
								}
							}
						}
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_DEVICE_POWER);
			i.putExtra("state", update);
			i.putExtra("tidarr", tidarrs.toString());
			mApp.sendBroadcast(i);
		}
	}

	@Override
	public Object check(String[] arg) {
		DEV_POWER[] ret = null;
		if((arg != null) && (arg.length > 0)){
			int size = arg.length;
			ret = new DEV_POWER[size];
			for(int i = 0; i < size; i++){
				String tid = arg[i];
				POWER_DATA pd = mDataMap.get(tid);
				if(pd == null){
					pd = new POWER_DATA(tid);
					mDataMap.put(tid, pd);
				}
				ret[i] = new DEV_POWER(tid, pd.power, pd.update);
			}
		}
		return ret;
	}

	@Override
	public boolean commit(Object data) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
